<?php

/**
 * AttachmentController.class.php 附件组件
 * Created Time 2016年3月23日 下午5:07:48
 *
 * @author     codingyuan@163.com
 */
namespace Component\Controller;

class AttachmentController {
    private $errcode = - 8;
    private $imgExts = array ();

    public function __construct()
    {

        $this->imgExts = C ('imgexts', null, array (
                'jpg', 
                'gif', 
                'png', 
                'jpeg' 
        ));
    }

    public function read()
    {
        try {
            // 验证参数的合法性
            $aid = I('get.id');
            $options = array();
            $options['download'] = I('get.download');
            
            if(!$aid || !is_numeric($aid))
            {
                throw new \Exception(L('_ERR_ATID_'));
            }
            
            $attService = D('Attachment','Service');
            if(!$attService->read($aid, $options))
            {
                return false;
            }
            
            $resp = \Component\Common\Response::get_instance();
            return $resp->stop();
            
        } catch (\Exception $e) {
            $errInfo = $e->getMessage ();
            return save_app_log($errInfo, 'component');
            // return get_api_result ('component', array (), $errInfo);
        }
        
    }

    public function upload()
    {

        try
        {
            $config = C ('upload');
            $upload = new \Think\Upload ($config);
            $info = $upload->upload ();
            $errmsg = null;
            if (! $info)
            {
                $errmsg = $upload->getError ();
                throw new \Exception ($this->errcode . ':' . $errmsg);
                // return get_api_result('component', array(), $this->errcode.':'.$errmsg);
            }
            $fileinfo = array ();
            $attData = array ();
            // 存储文件信息
            foreach ($info as $val)
            {
                $fileinfo ['atname'] = $val ['savename'];
                $fileinfo ['atpath'] = $val ['savepath'];
                $fileinfo ['atmine'] = $val ['type'];
                $fileinfo ['atext'] = $val ['ext'];
                $fileinfo ['created'] = time ();
                if (in_array ($val ['ext'], $this->imgExts))
                {
                    $fileinfo ['attype'] = 1;
                }
                $attData [] = $fileinfo;
            }
            $attModel = D ('Attachment');
            $rs = $attModel->data ($attData)->addAll ($attData);
            if (! $rs)
            {throw new \Exception (L ('_ERR_UPLOAD_'));}
            $attInfo = array();
            $attInfo['aid'] = $rs;
            $attInfo['att_url'] = set_attr_url($rs);
            
            return get_api_result ('component', $attInfo);
            
        } catch ( \Exception $e )
        {
            $errInfo = $e->getMessage ();
            return get_api_result ('component', array (), $errInfo);
        }
    }

}

